package com.gd.iot.energy.service.systemadmin.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gd.iot.energy.code.ResponseCode;
import com.gd.iot.energy.consts.SystemConsts;
import com.gd.iot.energy.dao.systemadmin.ArchivesChangePOMapper;
import com.gd.iot.energy.dao.systemadmin.AreaArchivesPOMapper;
import com.gd.iot.energy.dao.systemadmin.EquipConcentPOMapper;
import com.gd.iot.energy.exception.MyException;
import com.gd.iot.energy.po.systemadmin.ArchivesChangePO;
import com.gd.iot.energy.po.systemadmin.AreaArchivesPO;
import com.gd.iot.energy.po.systemadmin.EquipConcentPO;
import com.gd.iot.energy.pojo.common.vo.ColumnVO;
import com.gd.iot.energy.pojo.common.vo.PageVO;
import com.gd.iot.energy.pojo.systemadmin.dto.ArchivesChangeSaveDTO;
import com.gd.iot.energy.pojo.systemadmin.dto.AreaOrganizationSaveDTO;
import com.gd.iot.energy.pojo.systemadmin.dto.EquipmentmodelSaveDTO;
import com.gd.iot.energy.pojo.systemadmin.vo.ArchivesChangePageVO;
import com.gd.iot.energy.service.systemadmin.ArchivesChangeService;
import com.gd.iot.energy.service.systemadmin.AreaOrganizationService;
import com.gd.iot.energy.service.systemadmin.EquipmentmodelService;
import com.gd.iot.energy.util.CustomColumnUtil;
import com.gd.iot.energy.util.CustomStrUtil;
import com.gd.iot.energy.util.EnergyTypeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ArchivesChangeServiceImpl extends ServiceImpl<AreaArchivesPOMapper, AreaArchivesPO> implements ArchivesChangeService {
    @Resource
    private ArchivesChangePOMapper archivesChangePOMapper;

    @Resource
    private AreaArchivesPOMapper areaArchivesPOMapper;

    @Autowired
    private AreaOrganizationService areaOrganizationService;

    @Autowired
    private EquipmentmodelService equipmentmodelService;

    @Resource
    private EquipConcentPOMapper equipConcentPOMapper;

    /**
     * 表头文件
     */
    private static final String ARCHIVES_CHANGE_COLUMN_FILE_NAME = "systemadmin/archivesChange_list.column";

    @Override
    public PageVO<ArchivesChangePageVO> getArchivesChangePageVOs(Long areaOrg, String customerName, String customerSerialnumber, String serialnumber, Integer pageSize, Integer pageNo, String orderColumn, String orderType) {
        IPage<AreaArchivesPO> page = new Page<>(pageNo, pageSize);
        QueryWrapper<AreaArchivesPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", SystemConsts.BooleanEnum.FALSE.value);

        if (areaOrg != null) {
            List<Long> allChildAreaIds = areaOrganizationService.getAllChildAreaIds(BigDecimal.valueOf(areaOrg).intValue());
            if (CollUtil.isNotEmpty(allChildAreaIds)) {
                queryWrapper.in("measure_area_org", allChildAreaIds);
            }
        }

        if (StrUtil.isNotBlank(customerName)) {
            queryWrapper.like("customer_name", customerName.trim());
        }
        if (StrUtil.isNotBlank(customerSerialnumber)) {
            queryWrapper.like("customer_serialnumber", customerSerialnumber.trim());
        }
        if (StrUtil.isNotBlank(serialnumber)) {
            queryWrapper.like("serialnumber", serialnumber.trim());
        }
        if (StrUtil.isNotBlank(orderColumn) && StrUtil.isNotBlank(orderType)) {
            orderColumn = CustomStrUtil.humpToLine(orderColumn);
            queryWrapper.orderBy(true, orderType.equals(SystemConsts.OrderType.ASC.value), orderColumn);
        }
        EnergyTypeUtil.injectEnergyTypeWrapper(queryWrapper);
        IPage<AreaArchivesPO> areaArchivesPOIPage = areaArchivesPOMapper.selectPage(page, queryWrapper);
        PageVO<ArchivesChangePageVO> pageVO = new PageVO<>();
        pageVO.setPageSize(pageSize);
        pageVO.setPageNum(pageNo);
        List<ArchivesChangePageVO> metermodelPageVOS = convertToMetermodelPageVOList(areaArchivesPOIPage.getRecords(), pageSize, pageNo);
        pageVO.setData(metermodelPageVOS);
        pageVO.setTotal(areaArchivesPOIPage.getTotal());
        pageVO.setPages(areaArchivesPOIPage.getPages());

        //表头
        List<ColumnVO> columns = CustomColumnUtil.getColumn(ARCHIVES_CHANGE_COLUMN_FILE_NAME);
        pageVO.setColumns(columns);
        return pageVO;
    }

    /**
     * 对象转换
     *
     * @param records
     * @return
     */
    private List<ArchivesChangePageVO> convertToMetermodelPageVOList(List<AreaArchivesPO> records, Integer pageSize, Integer pageNo) {
        List<ArchivesChangePageVO> res = new ArrayList<>(records.size());
        ArchivesChangePageVO archivesChangePageVO;

        int i = pageSize * (pageNo - 1) + 1;
        for (AreaArchivesPO record : records) {
            archivesChangePageVO = new ArchivesChangePageVO();
            archivesChangePageVO.setSerialNum(i);
            archivesChangePageVO.setId(record.getId());
            archivesChangePageVO.setCustomerName(record.getCustomerName());
            archivesChangePageVO.setCustomerTypeName(SystemConsts.CustomerTypeEnum.getValueNameByValue(record.getCustomerType()));
            archivesChangePageVO.setCustomerSerialnumber(record.getCustomerSerialnumber());
            archivesChangePageVO.setCustomerStateName(SystemConsts.ArchivesCustomerStateEnum.getDescNameByValue(record.getCustomerState()));
            archivesChangePageVO.setCustomerPhone(record.getCustomerPhone());
            archivesChangePageVO.setCustomerPassword(record.getCustomerPassword());
            archivesChangePageVO.setCustomerUseStateName(SystemConsts.EnabledState.getValuenameByValue(record.getCustomerUseState()));
            archivesChangePageVO.setCustomerFee(record.getCustomerFee());
            archivesChangePageVO.setReading(record.getReading());
            res.add(archivesChangePageVO);
            i++;
        }
        return res;
    }

    @Override
    public ArchivesChangeSaveDTO getArchivesChange(Integer id) {
        AreaArchivesPO areaArchivesPO = areaArchivesPOMapper.selectById(id);
        if(areaArchivesPO==null||SystemConsts.BooleanEnum.TRUE.value.equals(areaArchivesPO.getIsDel())){
            throw new MyException(ResponseCode.RECORD_NOT_EXIST);
        }

        ArchivesChangeSaveDTO archivesChangeSaveDTO = new ArchivesChangeSaveDTO();
        archivesChangeSaveDTO.setId(areaArchivesPO.getId());
        archivesChangeSaveDTO.setCustomerName(areaArchivesPO.getCustomerName());
        archivesChangeSaveDTO.setCustomerSerialnumber(areaArchivesPO.getCustomerSerialnumber());
        archivesChangeSaveDTO.setSerialnumber(areaArchivesPO.getSerialnumber());
        archivesChangeSaveDTO.setNbonetNetImei(areaArchivesPO.getNbonetNetImei());
        archivesChangeSaveDTO.setSysconfigMeterModel(areaArchivesPO.getSysconfigMeterModel());
        archivesChangeSaveDTO.setResultInfo(areaArchivesPO.getMeterMemo());

        return archivesChangeSaveDTO;
    }

    @Override
    public boolean remove(ArchivesChangeSaveDTO archivesChangeSaveDTO) {
        ArchivesChangePO archivesChangePO = new ArchivesChangePO();
        AreaArchivesPO areaArchivesPO = areaArchivesPOMapper.selectById(archivesChangeSaveDTO.getId());
        areaArchivesPO.setModifyDate(new Date());
        areaArchivesPO.setOperatorId(1L);
        areaArchivesPO.setSerialnumber(null);
        if (SystemConsts.EquipmentType.NBIOT.value.equals(areaArchivesPO.getEquipmentType())) {
            archivesChangePO.setOldSerialnumber(areaArchivesPO.getSerialnumber());
            areaArchivesPO.setCustomerState(SystemConsts.ArchivesCustomerStateEnum.AP.value);
        } else {
            archivesChangePO.setOldNbonetNetImei(areaArchivesPO.getNbonetNetImei());
            EquipmentmodelSaveDTO equipmentmodel = equipmentmodelService.getEquipmentmodel(BigDecimal.valueOf(areaArchivesPO.getSysconfigEquipmentModel()).intValue());
            removeNb(areaArchivesPO, equipmentmodel);
            areaArchivesPO.setCustomerState(SystemConsts.ArchivesCustomerStateEnum.AP.value);
            areaArchivesPO.setNboneNetDeviceId(null);
        }
        areaArchivesPOMapper.updateById(areaArchivesPO);

        archivesChangePO.setCompanyId(0L);
        archivesChangePO.setCreateDate(new Date());
        archivesChangePO.setEnergyType(SystemConsts.EnergyTypeEnum.WATER.value);
        archivesChangePO.setIsDel(SystemConsts.BooleanEnum.FALSE.value);
        archivesChangePO.setModifyDate(new Date());
        archivesChangePO.setOperatorId(1L);
        archivesChangePO.setAreaArchivesId(areaArchivesPO.getId());
        archivesChangePO.setAreaOrgId(areaArchivesPO.getMeasureAreaOrg());
        AreaOrganizationSaveDTO areaOrganization = areaOrganizationService.getAreaOrganization(BigDecimal.valueOf(areaArchivesPO.getMeasureAreaOrg()).intValue());
        archivesChangePO.setAreaName(areaOrganization==null?"":areaOrganization.getName());
        archivesChangePO.setCustomerName(areaArchivesPO.getCustomerName());
        archivesChangePO.setCustomerSerialnumber(areaArchivesPO.getCustomerSerialnumber());
//        archivesChangePO.setDateTime(CustomDateUtil.parseDate(archivesChangeSaveDTO.getDateTime(), "yyyy-MM-dd hh:mm:ss"));
        archivesChangePO.setDateTime(new Date());
        archivesChangePO.setExecutionStatus(SystemConsts.ExecutionStatus.SUCCESS.value);
        archivesChangePO.setExecutionType(SystemConsts.ChType.REMOVE.value);
        archivesChangePO.setReadingnum(new BigDecimal(areaArchivesPO.getReading()));
        archivesChangePO.setResultInfo(archivesChangeSaveDTO.getResultInfo());

        archivesChangePOMapper.insert(archivesChangePO);
        return true;
    }

    @Override
    public boolean change(ArchivesChangeSaveDTO archivesChangeSaveDTO) {
        ArchivesChangePO archivesChangePO = new ArchivesChangePO();
        AreaArchivesPO areaArchivesPO = areaArchivesPOMapper.selectById(archivesChangeSaveDTO.getId());
        areaArchivesPO.setModifyDate(new Date());
        areaArchivesPO.setOperatorId(1L);

//        String deviceStr = "";
//        if (SystemConsts.EquipmentType.NBIOT.value.equals(areaArchivesPO.getEquipmentType())) {
//            archivesChangePO.setOldSerialnumber(areaArchivesPO.getSerialnumber());
//            areaArchivesPO.setSerialnumber(archivesChangeSaveDTO.getNewSerialnumber());
//            archivesChangePO.setNewSerialnumber(archivesChangeSaveDTO.getNewSerialnumber());
//        } else if (StrUtil.isNotBlank(archivesChangeSaveDTO.getNbonetNetImei())) {
//            archivesChangePO.setOldNbonetNetImei(areaArchivesPO.getNbonetNetImei());
//            EquipmentmodelSaveDTO equipmentmodel = equipmentmodelService.getEquipmentmodel(BigDecimal.valueOf(areaArchivesPO.getSysconfigEquipmentModel()).intValue());
//            removeNb(areaArchivesPO, equipmentmodel);
//
//            EquipConcentPO equipConcentPO = equipConcentPOMapper.selectById(areaArchivesPO.getMeasureEquipConcent());
//            if (SystemConsts.EquipmentNBType.MOBILE.value.equals(equipConcentPO.getEquipmentnbtype())) {
//                deviceStr = "MOBILE";
//            } else if (SystemConsts.EquipmentNBType.TELECOM.value.equals(equipConcentPO.getEquipmentnbtype())) {
//                deviceStr = "TELECOM";
//            } else if (SystemConsts.EquipmentNBType.UNION.value.equals(equipConcentPO.getEquipmentnbtype())) {
//                deviceStr = "UNION";
//            }
//            areaArchivesPO.setNboneNetDeviceId(deviceStr);
//            areaArchivesPO.setNbonetNetImei(archivesChangeSaveDTO.getNewNbonetNetImei());
//            archivesChangePO.setNewNbonetNetImei(archivesChangeSaveDTO.getNewNbonetNetImei());
//        }
        areaArchivesPO.setSysconfigMeterModel(archivesChangeSaveDTO.getNewSysconfigMeterModel());
        areaArchivesPOMapper.updateById(areaArchivesPO);

        archivesChangePO.setCompanyId(0L);
        archivesChangePO.setCreateDate(new Date());
        archivesChangePO.setEnergyType(SystemConsts.EnergyTypeEnum.WATER.value);
        archivesChangePO.setIsDel(SystemConsts.BooleanEnum.FALSE.value);
        archivesChangePO.setModifyDate(new Date());
        archivesChangePO.setOperatorId(1L);
        archivesChangePO.setAreaArchivesId(areaArchivesPO.getId());
        archivesChangePO.setAreaOrgId(areaArchivesPO.getMeasureAreaOrg());
        AreaOrganizationSaveDTO areaOrganization = areaOrganizationService.getAreaOrganization(BigDecimal.valueOf(areaArchivesPO.getMeasureAreaOrg()).intValue());
        archivesChangePO.setAreaName(areaOrganization==null?"":areaOrganization.getName());
        archivesChangePO.setCustomerName(areaArchivesPO.getCustomerName());
        archivesChangePO.setCustomerSerialnumber(areaArchivesPO.getCustomerSerialnumber());
//        archivesChangePO.setDateTime(CustomDateUtil.parseDate(archivesChangeSaveDTO.getDateTime(), "yyyy-MM-dd hh:mm:ss"));
        archivesChangePO.setDateTime(new Date());
        archivesChangePO.setExecutionStatus(SystemConsts.ExecutionStatus.SUCCESS.value);
        archivesChangePO.setExecutionType(SystemConsts.ChType.CHANGE.value);
        archivesChangePO.setReadingnum(new BigDecimal(areaArchivesPO.getReading()));
        archivesChangePO.setResultInfo(archivesChangeSaveDTO.getResultInfo());

        archivesChangePOMapper.insert(archivesChangePO);
        return true;
    }

    public boolean removeNb(final AreaArchivesPO archives, final EquipmentmodelSaveDTO equipmentModel) {
        return true;
    }
}
